<template>
  <div ref="drag" :style="computedStyle" :class="computedClass">
    <slot></slot>
    <div class="resize-wrapper">
      <div class="resize-area" @mousedown="mousedown"></div>
    </div>
  </div>
</template>
<script>
export default {
  name: "DDrag",
  props: {
    direction: {
      type: String,
      default: "x"
    },
    minWidth: {
      type: Number,
      default: 164
    },
    maxWidth: {
      type: Number,
      default: 480
    }
  },
  data() {
    return {
      show: true,
      width: 240,
      height: 400
    };
  },
  computed: {
    computedStyle() {
      let { width, minWidth, maxWidth, height } = this;
      if (width > maxWidth) {
        width = maxWidth;
      }
      if (width < minWidth) {
        width = minWidth;
      }
      if (this.direction == "x") {
        return { width: width + "px" };
      } else {
        return {
          height: `calc(100% - ${height}px)`
        };
      }
    },
    computedClass() {
      return ["data-drag", this.direction == "x" ? "left-to-right" : "top-to-bottom"];
    }
  },
  methods: {
    toggle() {
      this.show = !this.show;
      this.$emit("toggle", this.show);
    },
    mousedown(e) {
      this.isMouseDown = true;
      console.dir(this.$refs.drag);
      window.addEventListener("mousemove", this.moveHandler);
      window.addEventListener("mouseup", () => {
        this.isMouseDown = false;
        window.removeEventListener("mousemove", this.moveHandler);
      });
    },
    moveHandler(e) {
      e.preventDefault();
      if (!this.isMouseDown) {
        return;
      }
      this.width = e.clientX - 20;
      this.height = e.clientY - 120;
    }
  }
};
</script>
<style lang="scss">
.data-drag {
  position: relative;
  .resize-wrapper {
    position: absolute;
  }
  &.left-to-right {
    .resize-wrapper {
      top: 40%;
      right: 0;
      display: flex;
      height: 30px;
      align-items: center;
      .resize-area {
        cursor: col-resize;
        width: 6px;
        height: 100%;
        background: #888;
      }
    }
  }
  &.top-to-bottom {
    .resize-wrapper {
      position: absolute;
      display: flex;
      top: 0;
      left: 50%;
      width: 30px;
      align-items: center;
      .resize-area {
        cursor: row-resize;
        height: 6px;
        width: 100%;
        background: #888;
      }
    }
  }
}
</style>
